// React核心库导入
import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
// MCP工具服务导入
import mcpToolService, {
  McpToolDto,
  McpToolDetailDto,
  CreateMcpToolInput,
  UpdateMcpToolInput,
  ExecuteMcpToolInput,
  McpToolExecutionResultDto,
  McpToolTestResultDto,
  McpToolStatisticsDto,
  GetMcpToolListInput,
  McpToolStatus,
} from '@services/mcpToolService';
// 消息提示组件导入
import { message } from 'antd';

// 工具状态接口
interface McpToolState {
  // 工具列表数据
  tools: McpToolDto[];
  // 当前工具详情
  currentTool: McpToolDetailDto | null;
  // 加载状态
  loading: boolean;
  // 错误信息
  error: string | null;
  // 总数统计
  totalCount: number;
  // 过滤条件
  filters: GetMcpToolListInput;
  // 统计信息
  statistics: McpToolStatisticsDto | null;
  // 分类列表
  categories: string[];
  // 执行结果
  executionResult: McpToolExecutionResultDto | null;
  // 测试结果
  testResult: McpToolTestResultDto | null;
  // 执行历史
  executionHistory: McpToolExecutionResultDto[];
}

// 工具动作类型
type McpToolAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_TOOLS'; payload: { tools: McpToolDto[]; totalCount: number } }
  | { type: 'SET_CURRENT_TOOL'; payload: McpToolDetailDto | null }
  | { type: 'ADD_TOOL'; payload: McpToolDto }
  | { type: 'UPDATE_TOOL'; payload: McpToolDto }
  | { type: 'DELETE_TOOL'; payload: string }
  | { type: 'SET_FILTERS'; payload: Partial<GetMcpToolListInput> }
  | { type: 'SET_STATISTICS'; payload: McpToolStatisticsDto }
  | { type: 'SET_CATEGORIES'; payload: string[] }
  | { type: 'SET_EXECUTION_RESULT'; payload: McpToolExecutionResultDto }
  | { type: 'SET_TEST_RESULT'; payload: McpToolTestResultDto }
  | { type: 'ADD_EXECUTION_HISTORY'; payload: McpToolExecutionResultDto }
  | { type: 'CLEAR_EXECUTION_RESULT' }
  | { type: 'CLEAR_TEST_RESULT' }
  | { type: 'CLEAR_EXECUTION_HISTORY' };

// 初始状态
const initialState: McpToolState = {
  tools: [],
  currentTool: null,
  loading: false,
  error: null,
  totalCount: 0,
  filters: {
    skipCount: 0,
    maxResultCount: 10,
    sorting: 'usageCount desc,creationTime desc'
  },
  statistics: null,
  categories: [],
  executionResult: null,
  testResult: null,
  executionHistory: []
};

// Reducer函数
function mcpToolReducer(state: McpToolState, action: McpToolAction): McpToolState {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, loading: action.payload };

    case 'SET_ERROR':
      return { ...state, error: action.payload, loading: false };

    case 'SET_TOOLS':
      return {
        ...state,
        tools: action.payload.tools,
        totalCount: action.payload.totalCount,
        loading: false,
        error: null
      };

    case 'SET_CURRENT_TOOL':
      return { ...state, currentTool: action.payload, loading: false };

    case 'ADD_TOOL':
      return {
        ...state,
        tools: [action.payload, ...state.tools],
        totalCount: state.totalCount + 1
      };

    case 'UPDATE_TOOL':
      return {
        ...state,
        tools: state.tools.map(tool =>
          tool.id === action.payload.id ? action.payload : tool
        ),
        currentTool:
          state.currentTool?.id === action.payload.id
            ? {
                ...state.currentTool,
                ...action.payload,
                parameters: Array.isArray(action.payload.parameters) ? action.payload.parameters : state.currentTool.parameters
              }
            : state.currentTool
      };

    case 'DELETE_TOOL':
      return {
        ...state,
        tools: state.tools.filter(tool => tool.id !== action.payload),
        currentTool:
          state.currentTool?.id === action.payload ? null : state.currentTool,
        totalCount: state.totalCount - 1
      };

    case 'SET_FILTERS':
      return {
        ...state,
        filters: { ...state.filters, ...action.payload }
      };

    case 'SET_STATISTICS':
      return { ...state, statistics: action.payload };

    case 'SET_CATEGORIES':
      return { ...state, categories: action.payload };

    case 'SET_EXECUTION_RESULT':
      return { ...state, executionResult: action.payload };

    case 'SET_TEST_RESULT':
      return { ...state, testResult: action.payload };

    case 'ADD_EXECUTION_HISTORY':
      return {
        ...state,
        executionHistory: [action.payload, ...state.executionHistory].slice(0, 50) // 保留最近50条记录
      };

    case 'CLEAR_EXECUTION_RESULT':
      return { ...state, executionResult: null };

    case 'CLEAR_TEST_RESULT':
      return { ...state, testResult: null };

    case 'CLEAR_EXECUTION_HISTORY':
      return { ...state, executionHistory: [] };

    default:
      return state;
  }
}

// Context创建
const McpToolContext = createContext<{
  state: McpToolState;
  actions: {
    fetchTools: () => void;
    fetchToolDetail: (id: string) => void;
    createTool: (input: CreateMcpToolInput) => Promise<void>;
    updateTool: (id: string, input: UpdateMcpToolInput) => Promise<void>;
    deleteTool: (id: string) => Promise<void>;
    executeTool: (id: string, input: ExecuteMcpToolInput) => Promise<void>;
    testConnection: (id: string) => Promise<void>;
    fetchCategories: () => void;
    fetchStatistics: () => void;
    resetStats: (id: string) => Promise<void>;
    setStatus: (id: string, status: McpToolStatus) => Promise<void>;
    batchDelete: (ids: string[]) => Promise<void>;
    batchSetActive: (ids: string[], isActive: boolean) => Promise<void>;
    setFilters: (filters: Partial<GetMcpToolListInput>) => void;
    resetFilters: () => void;
    clearExecutionResult: () => void;
    clearTestResult: () => void;
    clearExecutionHistory: () => void;
  };
} | null>(null);

// Provider组件
interface McpToolProviderProps {
  children: ReactNode;
}

export const McpToolProvider: React.FC<McpToolProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(mcpToolReducer, initialState);

  // 获取工具列表
  const fetchTools = async () => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const { items, totalCount } = await mcpToolService.getMcpToolList(state.filters);
      dispatch({ type: 'SET_TOOLS', payload: { tools: items, totalCount } });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取工具列表失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 获取工具详情
  const fetchToolDetail = async (id: string) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const tool = await mcpToolService.getMcpToolDetail(id);
      dispatch({ type: 'SET_CURRENT_TOOL', payload: tool });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取工具详情失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 创建工具
  const createTool = async (input: CreateMcpToolInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const tool = await mcpToolService.createMcpTool(input);
      dispatch({ type: 'ADD_TOOL', payload: tool });
      message.success('工具创建成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建工具失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 更新工具
  const updateTool = async (id: string, input: UpdateMcpToolInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const tool = await mcpToolService.updateMcpTool(id, input);
      dispatch({ type: 'UPDATE_TOOL', payload: tool });
      message.success('工具更新成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新工具失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 删除工具
  const deleteTool = async (id: string) => {
    try {
      await mcpToolService.deleteMcpTool(id);
      dispatch({ type: 'DELETE_TOOL', payload: id });
      message.success('工具删除成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除工具失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 执行工具
  const executeTool = async (id: string, input: ExecuteMcpToolInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const result = await mcpToolService.executeMcpTool(id, input);
      dispatch({ type: 'SET_EXECUTION_RESULT', payload: result });
      dispatch({ type: 'ADD_EXECUTION_HISTORY', payload: result });
      
      if (result.isSuccess) {
        message.success('工具执行成功');
      } else {
        message.error('工具执行失败');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '执行工具失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 测试连接
  const testConnection = async (id: string) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const result = await mcpToolService.testMcpToolConnection(id);
      dispatch({ type: 'SET_TEST_RESULT', payload: result });
      
      if (result.isSuccess) {
        message.success('连接测试成功');
      } else {
        message.error('连接测试失败');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '测试连接失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const categories = await mcpToolService.getMcpToolCategories();
      dispatch({ type: 'SET_CATEGORIES', payload: categories });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取分类列表失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 获取统计信息
  const fetchStatistics = async () => {
    try {
      const statistics = await mcpToolService.getMcpToolStatistics();
      dispatch({ type: 'SET_STATISTICS', payload: statistics });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取统计信息失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 重置统计信息
  const resetStats = async (id: string) => {
    try {
      await mcpToolService.resetMcpToolStats(id);
      await fetchTools(); // 重新获取工具列表以更新统计
      message.success('统计信息已重置');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '重置统计失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 设置工具状态
  const setStatus = async (id: string, status: McpToolStatus) => {
    try {
      await mcpToolService.setMcpToolStatus(id, status);
      await fetchTools(); // 重新获取工具列表以更新状态
      message.success('工具状态已更新');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '设置状态失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 批量删除
  const batchDelete = async (ids: string[]) => {
    try {
      await mcpToolService.batchDeleteMcpTools(ids);
      ids.forEach(id => {
        dispatch({ type: 'DELETE_TOOL', payload: id });
      });
      message.success(`已删除 ${ids.length} 个工具`);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量删除失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 批量设置激活状态
  const batchSetActive = async (ids: string[], isActive: boolean) => {
    try {
      await mcpToolService.batchSetActiveMcpTools(ids, isActive);
      await fetchTools(); // 重新获取工具列表以更新状态
      message.success(`已${isActive ? '激活' : '停用'} ${ids.length} 个工具`);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量设置状态失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 设置过滤条件
  const setFilters = (filters: Partial<GetMcpToolListInput>) => {
    dispatch({ type: 'SET_FILTERS', payload: filters });
  };

  // 重置过滤条件
  const resetFilters = () => {
    dispatch({
      type: 'SET_FILTERS',
      payload: {
        skipCount: 0,
        maxResultCount: 10,
        sorting: 'usageCount desc,creationTime desc'
      }
    });
  };

  // 清除执行结果
  const clearExecutionResult = () => {
    dispatch({ type: 'CLEAR_EXECUTION_RESULT' });
  };

  // 清除测试结果
  const clearTestResult = () => {
    dispatch({ type: 'CLEAR_TEST_RESULT' });
  };

  // 清除执行历史
  const clearExecutionHistory = () => {
    dispatch({ type: 'CLEAR_EXECUTION_HISTORY' });
  };

  // 监听过滤条件变化，自动刷新数据
  useEffect(() => {
    fetchTools();
  }, [state.filters]);

  // 初始化数据
  useEffect(() => {
    fetchCategories();
    fetchStatistics();
  }, []);

  const actions = {
    fetchTools,
    fetchToolDetail,
    createTool,
    updateTool,
    deleteTool,
    executeTool,
    testConnection,
    fetchCategories,
    fetchStatistics,
    resetStats,
    setStatus,
    batchDelete,
    batchSetActive,
    setFilters,
    resetFilters,
    clearExecutionResult,
    clearTestResult,
    clearExecutionHistory
  };

  return (
    <McpToolContext.Provider value={{ state, actions }}>
      {children}
    </McpToolContext.Provider>
  );
};

// Hook函数
export const useMcpTool = () => {
  const context = useContext(McpToolContext);
  if (!context) {
    throw new Error('useMcpTool must be used within a McpToolProvider');
  }
  return context;
};

// 选择器Hook
export const useTools = () => {
  const { state } = useMcpTool();
  return state.tools;
};

export const useToolLoading = () => {
  const { state } = useMcpTool();
  return state.loading;
};

export const useToolError = () => {
  const { state } = useMcpTool();
  return state.error;
};

export const useToolFilters = () => {
  const { state, actions } = useMcpTool();
  return {
    filters: state.filters,
    setFilters: actions.setFilters,
    resetFilters: actions.resetFilters
  };
};

export const useCurrentTool = () => {
  const { state } = useMcpTool();
  return state.currentTool;
};

export const useToolStatistics = () => {
  const { state, actions } = useMcpTool();
  return {
    statistics: state.statistics,
    fetchStatistics: actions.fetchStatistics
  };
};

export const useToolCategories = () => {
  const { state } = useMcpTool();
  return state.categories;
};

export const useToolExecution = () => {
  const { state, actions } = useMcpTool();
  return {
    executionResult: state.executionResult,
    testResult: state.testResult,
    executeTool: actions.executeTool,
    testConnection: actions.testConnection,
    clearExecutionResult: actions.clearExecutionResult,
    clearTestResult: actions.clearTestResult
  };
};

export const useToolHistory = () => {
  const { state, actions } = useMcpTool();
  return {
    executionHistory: state.executionHistory,
    clearExecutionHistory: actions.clearExecutionHistory
  };
};